#!/usr/bin/python
import backend
import settings
import web
import simplejson as sj


clienthandler = backend.ClientHandler()
urls = (
    r'/','runcommand',
    r'/(?P<command>[a-zA-Z_]+)/','runcommand'
)

class runcommand:
    def GET(self,command=None):
        return sj.dumps(backend.commands())
        
    def POST(self,command=None):
        ###start authorization
        if command:
            if command not in backend.commands():
                return self.GET()
        args = web.input()
        if 'clientname' not in args:
            return 'Error: Clientname not provided.'
        if 'clientaction' not in args:
            return clienthandler.get_initial(args['clientname'])
        if args['clientaction'] == 'verify_key':
            if 'key' not in args or 'dsapub' not in args:
                return 'Error: Require key and dsapub to verify the key.'
            try:
                key = args['key'].decode('base64')
            except:
                return 'Error: Unable to decode key. Please encode using base64.'
            return clienthandler.verify_key(args['clientname'],key,args['dsapub'])
        if args['clientaction'] != 'verify_session' or 'key' not in args:
            return 'Error: Require signed session verification key.'
        result = clienthandler.verify_session(args['clientname'],args['key'])
        if type(result) == type(''):
            try:
                result = int(result)
            except:
                result = False
        if not result:
            return 'Error: Invalid session key.'
        ###stop authorization
        if 'args' not in args:
            return 'Error: Args required.'
        try:
            funcargs = sj.loads(args['args'])
        except:
            return 'Error: Unable to parse args. Please dictionary of args to JSON first.'
        if type(funcargs) == type([]):
            funcargs = tuple(funcargs)

        return backend.queuehandler.process(command,funcargs)

            
            
            

        
def main():
    app = web.application(urls,globals())
    app.run()

if __name__ == '__main__':
    main()
